package com.ruoyi.common.utils;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author anxin
 * @date 2024-12-23
 */
@Component
public class FilesUpLoadUtil {
    // 阿里云 OSS 配置
    @Value("${aliyun.oss.endpoint}")
    public  String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    public  String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    public  String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    public  String bucketName;

    @Value("${aliyun.oss.fileUploadDir}")
    public  String fileUploadDir;

    // 单文件上传
    public String uploadFileToOSS(byte[] fileBytes, String objectName) throws IOException {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建字节流输入流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);

            // 构造上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, byteArrayInputStream);

            // 上传文件
            ossClient.putObject(putObjectRequest);
            System.out.println("File uploaded successfully to OSS.");

            // 返回文件 URL
            String url = "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectName;
            System.out.println("OSS URL: " + url);
            return url;


        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("Error uploading file to OSS: " + e.getMessage());
        } finally {
            // 关闭 OSSClient
            ossClient.shutdown();
        }
    }

    // 多文件上传
    public List<String> uploadMultipleFiles(MultipartFile[] files) throws IOException {
        List<String> uploadedUrls = new ArrayList<>();

        for (MultipartFile file : files) {
            // 根据文件名生成唯一对象名
            String objectName = fileUploadDir + "/" + UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

            // 上传单个文件并记录 URL
            String fileUrl = uploadFileToOSS(file.getBytes(), objectName);
            System.out.println(fileUrl);
            uploadedUrls.add(fileUrl);
        }

        return uploadedUrls;
    }
}
